package com.fengchao.api.service;

import com.fengchao.api.config.Constant;
import com.fengchao.api.dao.bci.BciArtistInfoMapper;
import com.fengchao.api.dao.bci.BciArtistSummaryMapper;
import com.fengchao.api.dao.cfg.CfgApiConfigMapper;
import com.fengchao.api.dao.cfg.CfgChinaCityListMapper;
import com.fengchao.api.dao.cfg.CfgRegionMapper;
import com.fengchao.api.dao.svy.SvyUserWishRequestMapper;
import com.fengchao.api.dao.svy.SvyUserWishRequestResultMapper;
import com.fengchao.api.dao.svy.SvyUserWishRequestStatsMapper;
import com.fengchao.model.bci.BciArtistSummary;
import com.fengchao.model.cfg.CfgApiConfig;
import com.fengchao.model.cfg.CfgChinaCityList;
import com.fengchao.model.cfg.CfgRegion;
import com.fengchao.model.entity.comm.CustomBizException;
import com.fengchao.model.entity.comm.Message;
import com.fengchao.model.entity.comm.ResponseParameter;
import com.fengchao.model.svy.SvyUserWishRequest;
import com.fengchao.model.svy.SvyUserWishRequestResult;
import com.fengchao.model.svy.SvyUserWishRequestStats;
import com.fengchao.util.common.CommonValidator;
import com.fengchao.util.common.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by Administrator on 2016/7/13.
 */
@Service
public class SvyService {

    @Autowired
    SvyUserWishRequestMapper svyUserWishRequestMapper;
    @Autowired
    SvyUserWishRequestResultMapper svyUserWishRequestResultMapper;
    @Autowired
    CfgRegionMapper cfgRegionMapper;
    @Autowired
    BciArtistSummaryMapper bciArtistSummaryMapper;
    @Autowired
    CfgChinaCityListMapper cfgChinaCityListMapper;
    @Autowired
    BciArtistInfoMapper bciArtistInfoMapper;
    @Autowired
    CfgApiConfigMapper cfgApiConfigMapper;
    @Autowired
    SvyUserWishRequestStatsMapper svyUserWishRequestStatsMapper;


    /**
     * 添加心动艺人
     *
     * @param userId
     * @param cityId
     * @param wishArtistId
     * @return
     */
    @Transactional
    public ResponseParameter addWishArtist(Integer userId, Integer cityId, Integer wishArtistId) {
        ResponseParameter responseParameter = new ResponseParameter(Message.SUCCESS, Constant.ADD_SUCCESS);
        //效验城市id和艺人id是否正确
        CfgChinaCityList cfgChinaCityList = cfgChinaCityListMapper.findByCityId(cityId);
        if (cfgChinaCityList == null) {
            throw new CustomBizException(Constant.ILLEGAL_REQUEST);
        }
        BciArtistSummary bciArtistSummary = bciArtistSummaryMapper.selectByPrimaryKey(wishArtistId);
        if (bciArtistSummary == null) {
            throw new CustomBizException(Constant.ILLEGAL_REQUEST);
        }
        SvyUserWishRequest svyUserWishRequest = svyUserWishRequestMapper.findByUserIdAndWishArtistIdAndWishCityIdAndDate(userId, wishArtistId, cityId, DateUtil.getFormatDate(new Date(), DateUtil.DateFormat_yyyyMMdd));
        if (svyUserWishRequest != null) {
            responseParameter.setMessage(Constant.WISHREQUESTLIMIT);
            responseParameter.setStatus(Message.FAILURE);
            return responseParameter;
        }
        svyUserWishRequest = new SvyUserWishRequest();
        svyUserWishRequest.setUserId(userId);
        svyUserWishRequest.setWishArtistId(wishArtistId);
        svyUserWishRequest.setWishCityId(cityId);
        svyUserWishRequest.setWishTime(new Date());
        svyUserWishRequestMapper.insertSelective(svyUserWishRequest);
        return responseParameter;
    }

    /**
     * 统计心动排行榜
     *
     * @param wishArtistId
     * @param cityId
     */
    @Deprecated   //1.4以后 统一使用定时任务统计
    public void statisticslResult(Integer wishArtistId, Integer cityId) {
        SvyUserWishRequestResult svyUserWishRequestResult = svyUserWishRequestResultMapper.findByWishArtistIdAndWishCityId(wishArtistId, cityId);
        if (svyUserWishRequestResult == null) {
            //插入
            svyUserWishRequestResult = new SvyUserWishRequestResult();
            svyUserWishRequestResult.setWishArtistId(wishArtistId);
            svyUserWishRequestResult.setWishCityId(cityId);
            svyUserWishRequestResult.setWishCount(1);
            svyUserWishRequestResultMapper.insertSelective(svyUserWishRequestResult);
        } else {
            svyUserWishRequestResult.setWishCount(svyUserWishRequestResult.getWishCount() + 1);
            svyUserWishRequestResultMapper.updateByPrimaryKeySelective(svyUserWishRequestResult);
        }
    }


    /**
     * 获取心动的的结果
     *
     * @param page
     * @param count
     * @return
     */
    @Deprecated //1.4以后调整不区分城市  1.4之后强制更新去掉该方法
    public List<Map<String, Object>> getWishArtistResult(Integer page, Integer count) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        Integer start = (page - 1) * count;
        List<SvyUserWishRequestResult> svyUserWishRequestResultList = svyUserWishRequestResultMapper.findSvyUserWishRequestResultByOrderCount(start, count);
        Integer i = 1;
        for (SvyUserWishRequestResult svyUserWishRequestResult : svyUserWishRequestResultList) {
            Map<String, Object> resultMap = new HashMap<>();
            String ranking = i.toString();
            if (i < 10) {
                ranking = "0" + i;
            }
            BciArtistSummary bciArtistSummary = bciArtistSummaryMapper.selectByPrimaryKey(svyUserWishRequestResult.getWishArtistId());
            CfgRegion cfgRegion = cfgRegionMapper.selectByPrimaryKey(svyUserWishRequestResult.getWishCityId());
            resultMap.put("ranking", ranking);
            resultMap.put("image", bciArtistSummary != null ? bciArtistSummary.getHeadIconUrl() : "");
            String name = "";
            if (bciArtistSummary != null) {
                if (CommonValidator.isStringsNotNull(bciArtistSummary.getArtistNameEn())) {
                    name = bciArtistSummary.getArtistNameEn();
                }
                if (CommonValidator.isStringsNotNull(bciArtistSummary.getArtistNameCn())) {
                    name = bciArtistSummary.getArtistNameCn();
                }
                if (CommonValidator.isStringsNotNull(bciArtistSummary.getArtistNameEn()) && CommonValidator.isStringsNotNull(bciArtistSummary.getArtistNameCn())) {
                    name = bciArtistSummary.getArtistNameCn() + "(" + bciArtistSummary.getArtistNameEn() + ")";
                }
            }
            resultMap.put("name", name);
            resultMap.put("region", bciArtistSummary != null ? bciArtistSummary.getBirthAddr() : "");
            resultMap.put("cityName", cfgRegion == null ? "" : cfgRegion.getName());
            resultMap.put("count", svyUserWishRequestResult.getWishCount());
            i++;
            resultList.add(resultMap);
        }
        return resultList;
    }

    /**
     * 获取心动的的结果
     *
     * @param page
     * @param count
     * @return
     */
    public List<Map<String, Object>> getWishArtistResultV1(Integer page, Integer count) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        Integer start = (page - 1) * count;
        CfgApiConfig cfgApiConfig = cfgApiConfigMapper.findByKey(Constant.lastVoteSummaryVersion);
        List<Map> lists = svyUserWishRequestResultMapper.findMapByOrderCountAndGroupArtistAndVersionCode(cfgApiConfig.getValue(), start, count);
        Integer i = start + 1;
        for (Map map : lists) {
            Map<String, Object> resultMap = new HashMap<>();
            String ranking = i.toString();
            if (i < 10) {
                ranking = "0" + i;
            }
            BciArtistSummary bciArtistSummary = bciArtistSummaryMapper.selectByPrimaryKey(Integer.valueOf(map.get("wish_artist_id").toString()));
            resultMap.put("ranking", ranking);
            resultMap.put("image", bciArtistSummary != null ? bciArtistSummary.getHeadIconUrl() : "");
            String name = "";
            if (bciArtistSummary != null) {
                if (CommonValidator.isStringsNotNull(bciArtistSummary.getArtistNameEn())) {
                    name = bciArtistSummary.getArtistNameEn();
                }
                if (CommonValidator.isStringsNotNull(bciArtistSummary.getArtistNameCn())) {
                    name = bciArtistSummary.getArtistNameCn();
                }
                if (CommonValidator.isStringsNotNull(bciArtistSummary.getArtistNameEn()) && CommonValidator.isStringsNotNull(bciArtistSummary.getArtistNameCn())) {
                    name = bciArtistSummary.getArtistNameCn() + "(" + bciArtistSummary.getArtistNameEn() + ")";
                }
            }
            resultMap.put("name", name);
            resultMap.put("withArtistId", bciArtistSummary.getId());
            resultMap.put("region", bciArtistSummary != null ? bciArtistSummary.getBirthAddr() : "");
            resultMap.put("count", Integer.valueOf(map.get("wish_count").toString()));
            i++;
            resultList.add(resultMap);
        }
        return resultList;
    }


    /**
     * 根据艺人Id获取城市排名
     * 城市名 显示票数  显示目标 是否当天已投票
     *
     * @return
     */
    public Map getSvyCityByArtistId(Integer wishArtistId, Integer userId) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map> resultList = new ArrayList<>();
        CfgApiConfig cfgApiConfig = cfgApiConfigMapper.findByKey(Constant.lastVoteSummaryVersion);
        List<SvyUserWishRequestResult> svyUserWishRequestResults = svyUserWishRequestResultMapper.findByWishArtistId(wishArtistId, cfgApiConfig.getValue(), 0, 10);
        Integer ranking = 1;
        for (SvyUserWishRequestResult svyUserWishRequestResult : svyUserWishRequestResults) {
            SvyUserWishRequest svyUserWishRequest = svyUserWishRequestMapper.findByUserIdAndWishArtistIdAndWishCityIdAndDate(userId, wishArtistId, svyUserWishRequestResult.getWishCityId(), DateUtil.getFormatDate(new Date(), DateUtil.DateFormat_yyyyMMdd));
            CfgChinaCityList cfgChinaCityList = cfgChinaCityListMapper.findByCityId(svyUserWishRequestResult.getWishCityId());
            Map<String, Object> map = new HashMap<>();
            map.put("cityId", cfgChinaCityList.getCityId());
            map.put("cityName", cfgChinaCityList.getCityName());
            map.put("voteCount", svyUserWishRequestResult.getWishCount());
            map.put("voteTarget", cfgChinaCityList.getCrowdfundingGoalCount());
            map.put("ranking", ranking++);
            map.put("isVote", svyUserWishRequest == null ? 0 : 1);
            resultList.add(map);
        }
        BciArtistSummary bciArtistSummary = bciArtistSummaryMapper.selectByPrimaryKey(wishArtistId);
        resultMap.put("image", bciArtistSummary != null ? bciArtistSummary.getHeadIconUrl() : "");
        String name = "";
        if (bciArtistSummary != null) {
            if (CommonValidator.isStringsNotNull(bciArtistSummary.getArtistNameEn())) {
                name = bciArtistSummary.getArtistNameEn();
            }
            if (CommonValidator.isStringsNotNull(bciArtistSummary.getArtistNameCn())) {
                name = bciArtistSummary.getArtistNameCn();
            }
            if (CommonValidator.isStringsNotNull(bciArtistSummary.getArtistNameEn()) && CommonValidator.isStringsNotNull(bciArtistSummary.getArtistNameCn())) {
                name = bciArtistSummary.getArtistNameCn() + "(" + bciArtistSummary.getArtistNameEn() + ")";
            }
        }
        resultMap.put("name", name);
        resultMap.put("region", bciArtistSummary != null ? bciArtistSummary.getBirthAddr() : "");
        resultMap.put("cityList", resultList);
        return resultMap;
    }

    /**
     * 获取心动投票城市
     *
     * @return
     */
    public Map<String, Object> getSvyCity() {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> popList = new ArrayList<>();
        List<CfgChinaCityList> cfgChinaCityLists = cfgChinaCityListMapper.findByRecommanded();
        for (CfgChinaCityList cfgChinaCityList : cfgChinaCityLists) {
            Map<String, Object> pop = new HashMap<>();
            pop.put("id", cfgChinaCityList.getCityId());//城市id
            pop.put("name", cfgChinaCityList.getCityName());//城市名
            popList.add(pop);
        }
        List<CfgChinaCityList> cfgChinaCityLists1 = cfgChinaCityListMapper.findAll();
        List<Map<String, Object>> cityList = new ArrayList<>();
        Map<String, List<Map>> map = new TreeMap<>();
        for (CfgChinaCityList cfgChinaCityList : cfgChinaCityLists1) {
            List<Map> list = map.get(cfgChinaCityList.getCityGroupAbbr());
            Map<String, Object> cityMap = new HashMap<>();
            cityMap.put("id", cfgChinaCityList.getCityId());
            cityMap.put("name", cfgChinaCityList.getCityName());
            if (list == null) {
                list = new ArrayList<>();
                list.add(cityMap);
                map.put(cfgChinaCityList.getCityGroupAbbr(), list);
            } else {
                list.add(cityMap);
            }
        }
        for (String key : map.keySet()) {
            Map<String, Object> tempMap = new HashMap<>();
            tempMap.put("letter", key.toUpperCase());
            tempMap.put("letterList", map.get(key));
            cityList.add(tempMap);
        }
        resultMap.put("cityList", cityList);
        resultMap.put("popList", popList);
        resultMap.put("date", Long.valueOf(cfgApiConfigMapper.findByKey(Constant.cityListUpdateDate).getValue()));
        return resultMap;
    }

    /**
     * 获取前5个城市的排名前十的艺人的接口
     * <p>
     * 城市名 城市的排名  城市的所有票，城市上升排名
     * 艺人头像 名字 票数 排名数 是否可投票
     *
     * @return
     */
    public Map getArtistByCity(Integer userId) {
        Map resultMap = new HashMap();
        String versionCode = cfgApiConfigMapper.findByKey(Constant.lastVoteSummaryVersion).getValue();
        List<SvyUserWishRequestStats> svyUserWishRequestStatses = svyUserWishRequestStatsMapper.findByVersionCode(versionCode);
        List<Map> resultList = new ArrayList<>();
        //Integer ranking = 1;
        for (SvyUserWishRequestStats svyUserWishRequestStats : svyUserWishRequestStatses) {
            CfgChinaCityList cfgChinaCityList = cfgChinaCityListMapper.findByCityId(svyUserWishRequestStats.getWishCityId());
            Map<String, Object> map = new HashMap<>();
            map.put("cityId", cfgChinaCityList.getCityId());
            map.put("cityName", cfgChinaCityList.getCityName());
            map.put("ranking", svyUserWishRequestStats.getRanking());
            map.put("voteCount", svyUserWishRequestStats.getWishCount());
            map.put("rankingChangeStatus", svyUserWishRequestStats.getRankingChangeStatus());
            map.put("rankingChangeCount", svyUserWishRequestStats.getRankingChangeCount());
            List<SvyUserWishRequestResult> svyUserWishRequestResults = svyUserWishRequestResultMapper.findByWishCityIdAndVersionCode(svyUserWishRequestStats.getWishCityId(), versionCode, 0, 10);
            List<Map> list = new ArrayList<>();
            Integer artistRank = 1;
            for (SvyUserWishRequestResult svyUserWishRequestResult : svyUserWishRequestResults) {
                BciArtistSummary bciArtistSummary = bciArtistSummaryMapper.selectByPrimaryKey(svyUserWishRequestResult.getWishArtistId());
                String name = "";
                if (bciArtistSummary != null) {
                    if (CommonValidator.isStringsNotNull(bciArtistSummary.getArtistNameEn())) {
                        name = bciArtistSummary.getArtistNameEn();
                    }
                    if (CommonValidator.isStringsNotNull(bciArtistSummary.getArtistNameCn())) {
                        name = bciArtistSummary.getArtistNameCn();
                    }
                    if (CommonValidator.isStringsNotNull(bciArtistSummary.getArtistNameEn()) && CommonValidator.isStringsNotNull(bciArtistSummary.getArtistNameCn())) {
                        name = bciArtistSummary.getArtistNameCn() + "(" + bciArtistSummary.getArtistNameEn() + ")";
                    }
                }
                Map<String, Object> artistMap = new HashMap<>();
                artistMap.put("headIcon", bciArtistSummary != null ? bciArtistSummary.getHeadIconUrl() : "");//头像
                artistMap.put("artistId", bciArtistSummary.getId());
                artistMap.put("artistName", name);
                artistMap.put("voteCount", svyUserWishRequestResult.getWishCount());
                artistMap.put("artistRank", artistRank++);
                SvyUserWishRequest svyUserWishRequest = svyUserWishRequestMapper.findByUserIdAndWishArtistIdAndWishCityIdAndDate(userId, svyUserWishRequestResult.getWishArtistId(), svyUserWishRequestResult.getWishCityId(), DateUtil.getFormatDate(new Date(), DateUtil.DateFormat_yyyyMMdd));
                artistMap.put("isVote", svyUserWishRequest == null ? 0 : 1);
                list.add(artistMap);
            }
            map.put("artistList", list);
            resultList.add(map);
        }
        resultMap.put("info", resultList);
        return resultMap;
    }
}